import java.util.LinkedList;
import java.util.Queue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:${USER}
 * Date:${YEAR}-${MONTH}-${DAY}
 * ${TIME}
 */
public class Main {
    int[] dx={0,0,-1,1};
    int[] dy={1,-1,0,0};
    int m,n;
    boolean[][] visted;
    public int nearestExit(char[][] maze, int[] entrance) {
        m=maze.length;
        n=maze[0].length;
        visted=new boolean[m][n];
        Queue<int[]> queue=new LinkedList<>();
        queue.add(new int[]{entrance[0],entrance[1]});
        visted[entrance[0]][entrance[1]]=true;
        int step=0;
        while (!queue.isEmpty()){
            step++;
            int size=queue.size();
            for (int i = 0; i < size; i++) {
                int[] tmp=queue.poll();
                int a=tmp[0];int b=tmp[1];
                for (int k = 0; k < 4; k++) {
                    int x=dx[k]+a;int y=dy[k]+b;
                    if(x>=0&&x<m&&y>=0&&y<n&&maze[x][y]=='.'&&visted[x][y]==false){
                        if(x==0||x==m-1||y==0||y==n-1)return step;
                        visted[x][y]=true;
                        queue.add(new int[]{x,y});
                    }

                }
            }
        }
        return -1;
    }
}